package com.djx.auth.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.djx.auth.romten.UserRomtenService;
import com.djx.auth.service.AuthService;
import com.djx.common.constants.JwtConstants;
import com.djx.common.domain.User;
import com.djx.common.domain.response.UserResponse;
import com.djx.common.result.Result;
import com.djx.common.utils.JwtUtils;
import com.djx.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.UUID;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    @Resource
    private UserRomtenService userRomtenService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result<UserResponse> doLogin(User user) {
        if (StringUtils.isAllEmpty(user.getUsername(),user.getPassword())){
            return Result.error("用户名密码不能为空");
        }
        Result<User> result = userRomtenService.findUser(user);
        User data = result.getData();
        if (data==null){
            return Result.error("用户名密码不正确");
        }
        String userKey = UUID.randomUUID().toString();
        String token = JwtUtils.createToken(new HashMap<String, Object>() {{
            put(JwtConstants.USER_KEY, userKey);
        }});
        redisTemplate.opsForValue().set("user", JSONObject.toJSONString(data));
        UserResponse userResponse = new UserResponse();
        userResponse.setToken(token);
        userResponse.setMessage("登录成功");
        return Result.success(userResponse);
    }
}
